package com.marui.mianshi.thread.pool;

import java.util.concurrent.*;

/**
 * @author marui
 * @date 2020/4/15 9:14
 * @since 1.0
 * 自定义线程池
 *
 */
public class ThreadPoolDemo {

    public static void main(String[] args) {
        // 核心线程数
        int coreThreads = 2;
        // 最大线程数
        int maxThreads = 5;
        // 空闲线程存活时间
        long keepAliveTime = 2L;
        // 阻塞队列
        BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(3);
        // 拒绝策略
        ThreadPoolExecutor.AbortPolicy rejectPolicy = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = customThreadPool(coreThreads, maxThreads, keepAliveTime, blockingQueue, rejectPolicy);


        try {
            for (int i = 0; i < 9; i++) {
                threadPoolExecutor.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"执行");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        } finally {
            threadPoolExecutor.shutdown();
        }


    }

    private static ThreadPoolExecutor customThreadPool(int coreThreads,int maxThreads,long keepAliveTime,BlockingQueue<Runnable> blockingQueue,ThreadPoolExecutor.AbortPolicy rejectPolicy) {

        return new ThreadPoolExecutor(coreThreads, maxThreads,
                keepAliveTime, TimeUnit.SECONDS,
                blockingQueue, Executors.defaultThreadFactory(),rejectPolicy);
    }

}
